//
//  GamingViewController.m
//  LanQiuQuan
//
//  Created by TonyGenius on 16/3/5.
//  Copyright © 2016年 Rip. All rights reserved.
//

#import "GamingViewController.h"
#import <CoreLocation/CoreLocation.h>


@interface GamingViewController ()<UITableViewDataSource, UITableViewDelegate, searchDelegate, UIScrollViewDelegate>
{
    XMTabBarController *_tab;
    
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UIView *pushDownView;

@property (nonatomic, assign) NSInteger currPage;

@property (nonatomic, assign) NSInteger pageSize;

@property (nonatomic, strong) NSMutableArray *playgroundList;

@property (nonatomic, assign) NSInteger selectMode;

@end

@implementation GamingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavTab];
    [self registTableView];
    
    _selectMode = 101;
    _currPage = 0;
    _pageSize = 10;
    _playgroundList = [NSMutableArray array];
    
    
    __weak GamingViewController *weakSelf = self;
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf requestToTop];
    }];
    
    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf requestToBottom];
    }];
    [_tableView.mj_header beginRefreshing];
}

- (void)addressInfoToView:(NSDictionary *)dictionary andCoordinate:(CLLocationCoordinate2D)locationCoordinate2D
{
    NSLog(@"%@",dictionary);
}

#pragma mark -netWorking

- (void)requestToTop
{
    NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:0];
    switch (_selectMode) {
        case 101:
        {
            _currPage = 1;
            NSString *url = [NSString stringWithFormat:@"%@pageSize=%ld&currentPage=%ld",kURLFORPLAYGROUNDLIST,(long)_pageSize,(long)_currPage];
            NSString *urlForPlayGround = [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            [NetWorkEngin getRequestWithParametes:urlForPlayGround andBody:nil andFinishBlock:^(NSDictionary *respondData, NSError *error) {
                [_playgroundList removeAllObjects];
                
                [_playgroundList addObjectsFromArray:[jsonHelper jsonForPlayGroundWithDictionary:respondData]];
                [_tableView.mj_header endRefreshing];
                [_tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationMiddle];
                
            }];
        }
            break;
        case 102:
        {
            
        }
            break;
        case 103:
        {
            [NetWorkEngin getRequestWithParametes:kURLFORCITYTEAM andBody:nil andFinishBlock:^(NSDictionary *respondData, NSError *error) {
                [_playgroundList removeAllObjects];
                
                [_playgroundList addObjectsFromArray:[jsonHelper jsonForCityTeamWithDictionary:respondData]];
                [_tableView.mj_header endRefreshing];
                [_tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationRight];
                
            }];
        }
            break;
        default:
            break;
    }
    
}

- (void)requestToBottom
{
    if (_selectMode == 101) {
        _currPage += 1;
        NSString *url = [NSString stringWithFormat:@"%@pageSize=%ld&currentPage=%ld",kURLFORPLAYGROUNDLIST,(long)_pageSize,(long)_currPage];
        NSString *urlForPlayGround = [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        [NetWorkEngin getRequestWithParametes:urlForPlayGround andBody:nil andFinishBlock:^(NSDictionary *respondData, NSError *error) {
            
            [_playgroundList addObjectsFromArray:[jsonHelper jsonForPlayGroundWithDictionary:respondData]];
            [_tableView.mj_footer endRefreshing];
            [_tableView reloadData];
        }];
    }
    else
    {
        [_tableView.mj_footer endRefreshing];
    }
}


- (void)viewWillAppear:(BOOL)animated
{
    _tab =(XMTabBarController *) self.tabBarController;
    [_tab xmTabBarHidden:NO animated:YES];
    NSLog(@"城市%@___省份%@__%@",_tab.cityCode,_tab.provice,_tab.location);
}

#pragma mark -initView

- (void)registTableView
{
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tableViewBG"]];
    [_tableView setBackgroundView:imageView];
    [_tableView registerNib:[UINib nibWithNibName:@"GamingFieldTableViewCell" bundle:nil] forCellReuseIdentifier:kGAMINGCELL];
    [_tableView registerNib:[UINib nibWithNibName:@"PlayerTableViewCell" bundle:nil] forCellReuseIdentifier:kPLAYERCELL];
    [_tableView registerNib:[UINib nibWithNibName:@"myTeamsTableViewCell" bundle:nil] forCellReuseIdentifier:kMYTEAMSCELL];
}

- (void)initNavTab
{
    [self.navigationController.navigationBar setBarTintColor:[UIColor lightGrayColor]];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationItem.title = @"约球";
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"barBG"] forBarMetrics:UIBarMetricsDefault];
    
//    UIBarButtonItem *oneItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(itemAdd)];
//    UIBarButtonItem *addItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@""] style:UIBarButtonItemStyleDone target:self action:@selector(itemAdd)];
    
    UIBarButtonItem *twoItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"changeBtn"] style:UIBarButtonItemStyleDone target:self action:@selector(pushDown)];
    
//    [oneItem setTintColor:[UIColor whiteColor]];
    [twoItem setTintColor:[UIColor whiteColor]];
    
//    NSArray *Items = [NSArray arrayWithObjects:twoItem,oneItem, nil];
//    self.navigationItem.rightBarButtonItems = Items;
    
    self.navigationItem.rightBarButtonItem = twoItem;
}

- (void)itemAdd
{
    
}

- (void)pushDown
{
    _pushDownView.hidden = !_pushDownView.hidden;
}

- (IBAction)nearByPlayground:(id)sender {

    MapViewController *mapViewController = [[MapViewController alloc] init];
    [self.navigationController pushViewController:mapViewController animated:YES];
    
    _pushDownView.hidden = !_pushDownView.hidden;
    
}

- (IBAction)cityTeamBtn:(id)sender {
    
    CityTeamViewController *cityTeamVC = [[CityTeamViewController alloc] init];
    
    [self.navigationController pushViewController:cityTeamVC animated:YES];
    
    _pushDownView.hidden = !_pushDownView.hidden;
}

- (IBAction)selectBtn:(UIButton *)sender {
    NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:0];
    switch (sender.tag) {
        case 101:
        {
            _selectMode = sender.tag;
            [_tableView.mj_header beginRefreshing];
            _pushDownView.hidden = !_pushDownView.hidden;
        }
            break;
        case 102:
        {
            _selectMode = sender.tag;
//            [_tableView.mj_header beginRefreshing];
            [_tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationLeft];
            _pushDownView.hidden = !_pushDownView.hidden;
        }
            break;
        case 103:
        {
            _selectMode = sender.tag;
            [_tableView.mj_header beginRefreshing];
            _pushDownView.hidden = !_pushDownView.hidden;
        }
            break;
        default:
            break;
    }
}

#pragma mark -UITableViewDataSource
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor clearColor];
    SHSearchView *search = [[NSBundle mainBundle] loadNibNamed:@"SHSearchView" owner:self options:nil][0];
    
    search.frame = CGRectMake(0, 0, view.bounds.size.width, view.bounds.size.height);
    search.backgroundColor = [UIColor clearColor];
    [view addSubview:search];
    search.searchBar.placeholder = @"查找球队或球员";
    
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_selectMode == 101) {
        GamingFieldTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kGAMINGCELL forIndexPath:indexPath];
        PlayGroundModel *model = _playgroundList[indexPath.row];
        
        cell.detialLab.text = [NSString stringWithFormat:@"%@%@%@",model.cityName,model.adName,model.address];
        cell.nameLab.text = model.name;
        NSArray *locationArray = [model.location componentsSeparatedByString:@","];
        double lat = [locationArray[1] doubleValue];
        double lon = [locationArray[0] doubleValue];
        //    NSLog(@"球场经纬度：%f___%f",lat,lon);
        CLLocation *location = [[CLLocation alloc] initWithLatitude:lat longitude:lon];
        
        CLLocationDistance kilometers = [location distanceFromLocation:_tab.location]/1000;
        //    NSLog(@"%f",kilometers);
        cell.distanceLab.text = [NSString stringWithFormat:@"%.2fKM",kilometers];
        
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if (_selectMode == 102)
    {
        PlayerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"playerCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else
    {
        myTeamsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kMYTEAMSCELL forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        TeamModel *model = _playgroundList[indexPath.row];
        //    cell.teamName.text = model.name;
        [cell.nameBtn setTitle:model.name forState:UIControlStateNormal];
        cell.winTimes.text = [NSString stringWithFormat:@"%@胜%@负",model.winTimes,model.lostTimes];
        cell.teamPlayers.text = [NSString stringWithFormat:@"%@/100",model.peopleCount];
        NSLog(@"%@___%@",model.winTimes,model.peopleCount);
        return cell;
    }
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_selectMode == 102) {
        return 10;
    }
    return _playgroundList.count;
}


#pragma mark -UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 93;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (_selectMode == 101) {
        GamingFieldTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.backGroundImage.highlighted = YES;
        
        PlayGroundModel *model = _playgroundList[indexPath.row];
        NSArray *locationArray = [model.location componentsSeparatedByString:@","];
        double lat = [locationArray[1] doubleValue];
        double lon = [locationArray[0] doubleValue];
        //    NSLog(@"球场经纬度：%f___%f",lat,lon);
        CLLocation *location = [[CLLocation alloc] initWithLatitude:lat longitude:lon];
        
        MapViewController *mapViewController = [[MapViewController alloc] init];
        
        mapViewController.location = location;
        mapViewController.addressName = cell.nameLab.text;
        mapViewController.addName = cell.detialLab.text;
        [self.navigationController pushViewController:mapViewController animated:YES];
        cell.backGroundImage.highlighted = NO;

    }else if(_selectMode == 102)
    {
        
    }
    else
    {
        
    }
    
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_selectMode == 101) {
        GamingFieldTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.backGroundImage.highlighted = NO;
    }else if (_selectMode == 102)
    {
        
    }
    else
    {
        
    }
    }


#pragma mark -UIScrollViewDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (_pushDownView.hidden == NO) {
        _pushDownView.hidden = !_pushDownView.hidden;
    }
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
